package iit.projects.etaxi.model.dao;

import iit.projects.etaxi.model.entity.Message;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateMessageDao extends HibernateDaoSupport implements
		MessageDao {
	
	final Logger log = LoggerFactory.getLogger(HibernateMessageDao.class);

	@Override
	public void deleteMessages(List<Message> messages) {
		
		if(messages == null || messages.isEmpty()){
			return;
		}
		
		Session session = getSession(false);
		try{
			for(Message message : messages){
				if(log.isDebugEnabled()){
					log.debug("Going to Delete message " + message.getMessage());
				}
				session.delete(message);
			}
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}

	@Override
	public void saveMessages(List<Message> messages) {
		if(messages == null || messages.isEmpty()){
			return;
		}
		
		Session session = getSession(false);
		try{
			for(Message message : messages){
				if(log.isDebugEnabled()){
					log.debug("Going to Save message " + message.getMessage());
				}
				session.persist(message);
			}
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}

	@Override
	public List<Message> updateMessages(List<Message> messages) {
		if(messages == null || messages.isEmpty()){
			return messages;
		}
		
		Session session = getSession(false);
		List<Message> savedMessages = new ArrayList<Message>();
		try{
			for(Message message : messages){
				if(log.isDebugEnabled()){
					log.debug("Going to Update message " + message.getMessage());
				}
				savedMessages.add((Message)session.merge(message));
			}
			return savedMessages;
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Message> findAllMessages(){
		try{
			List<Message> messages = getHibernateTemplate().find("from Message o order by o.date desc");
			return messages;
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}

}
